define(['jquery', "controller", "mapController", "moniter","plantController","coordtransform"], function ($) {

    var c = require("controller");
    var ws = require("moniter");
    var mapController = require("mapController");
    var plantController=require("plantController");
    var coordtransform=require("coordtransform");

    mapTools={
        isShowLine:function (pl) {
            pl.isShowLine=!pl.isShowLine;
            for (var did in pl.flights) {
                if (pl.isShowLine) {
                    pl.showLineById(did);
                } else {
                     pl.hideLineById(did);
                }
            }

        }
    };

    var currentTimeStep = 1;
    getTime();
    function getTime() {
        c.ajax({
            url:'t',
            success:function (result) {
                ws.set_now_ts(result*1);
                currentTime = result*1;
            }
        });
    }
    window.setInterval(function () {
        if(currentTimeStep==60){
            currentTimeStep = 1;
            getTime();
        }else{
            ws.set_now_ts(ws.now_ts()+1);
            currentTimeStep++;
        }
    },1000);




    var infoWindowOpt={};
    return {
        init: function () {
            var mapCenter=c.getValues("mapCenter")?c.getValues("mapCenter").split(','):[104.2272944, 30.5729027];//[104.2272944, 30.5729027]
            var mapZoom=parseInt(c.getValues("mapZoom"))||10;
            var mapStyle=c.getValues("mapStyle")?c.getValues("mapStyle").split(','):[];
            var map = mapController.initMap();
            var theight = $(window).height() - 50;
            $(".content").height(theight);

            map.init('container',{
                center:mapCenter,
                zoom:mapZoom
            });
            var Satellite=map.setMapType();
            map.setMapControl();
            $(".maptype>div:eq(0)").on('click',function () {
                Satellite.hide();
            });
            $(".maptype>div:eq(1)").on('click',function () {
                Satellite.show();
            });

            $.each(mapStyle,function (i,v) {
                mapStyle[i]=parseInt(v);
                $('input[value="'+v+'"]').prop("checked","checked");
            });

            var pl=new plantController.plane(map,ws);

            var spaceLine=new plantController.drawSpaceLine(map,mapStyle);


            /*$('#container').on('click','a.my-info-close',function (e) {
                var did=$(this).attr('data-id');
                pl.flights[did].marker.hideInfoWindow();
             });*/


            /*开始飞行监控*/
            c.plInterval=setInterval(function () {
                var ponints=ws.consumer_point();
                $.each(ponints,function (i,ponint) {
                  /* var gj= coordtransform.wgs84togcj02(ponint.lng,ponint.lat);
                    ponint.lng=gj[0];
                    ponint.lat=gj[1];*/
                    pl.initFlight(ponint);
                    //aircraft_list.reLoad();
                })

            },1000/ws.frame_num);
            map.addEventListener("mousemove", function (lnglat) {
                var lnglat84=coordtransform.gcj02towgs84(lnglat.lng,lnglat.lat)
                $('#hander-infos>.lng>span').text(mapController.changeLngToDMS(lnglat84[0]));
                $('#hander-infos>.lat>span').text(mapController.changeLatToDMS(lnglat84[1]));
            });

            map.addEventListener("zoomchange", function () {
                c.setValues("mapZoom",map.getZoom())
            });

            map.addEventListener("moveend", function () {
                var center=map.getCenter();
                c.setValues("mapCenter",[center.lng,center.lat])
            });

            /* 刷新table数据 */
            function get_aircraft_list_html() {
                var rows = [];
                for (var id in pl.flights) {
                    var point = pl.flights[id].point;
                    rows.push('<tr><td><a href="#" class="list-table-a">' + id + '</a></td><td>' + point.lat + '</td><td>' + point.lng + '</td><td>' + point.height + '</td><td>' + point.speed + '</td><td>' + point.course + '</td></tr>');
                }
                return '<table id="tbl-tip" class="display" cellspacing="0" width="100%"><thead><tr><th>飞机</th><th>纬度</th><th>经度</th><th>高度</th><th>航速</th><th>航向</th></tr></thead><tbody>' + rows.join('') + "</tbody></table>";
            }
            /* 查看数据喽~~ */
            function view_plane(did) {
                map.setCenter(pl.flights[did].marker.getPosition());
                map.setZoom(13);
                pl.flights[did].marker.setIcon(pl.flights[did].selIcon,[32,32]);
/*                pl.infoWindow.setContent(mapController.get_popup_txt(pl.flights[did].point));
                pl.infoWindow.open(map,pl.flights[did].marker.getPosition());*/

               // $('.flight-list').parent().click();
            }
            $('#tip').on('click','a.list-table-a',function () {//列表飞行器点击事件

                aircraft_list.view_plane($(this).text())
            });


            var aircraft_list ={
                isCreate:true,
                dataTable:null,
                init:function () {
                    if(this.isCreate){
                        this.dataTable = c.myDataTable($(".customer-table"), {
                            data:this.getData(),
                            scrollY: (300) + "px",
                            scrollCollapse: true,
                            serverSide:false,
                            ordering:true,
                            dom:
                            "<'row'<'col-sm-6'f>>" +
                            "<'row'<'col-sm-12'tr>>" +
                            "<'row'<'col-sm-5'i><'col-sm-7'p> >",
                            columns: [
                                {"data": "id",
                                    "render": function (data) {
                                        return '<a href="#" class="list-table-a">'+data+'</a>';
                                    }},
                                {"data": "lng"},
                                {"data": "lat"},
                                {"data": "height"},
                                {"data": "speed"},
                                {"data": "course"}
                            ]
                        });
                        this.isCreate=false
                    }else{
                        this.reLoad();
                    }

                },
                getData:function () {
                    var data=[];
                    $.each(pl.flights,function (id,flight) {
                        var lnglat=coordtransform.gcj02towgs84(flight.point.lng,flight.point.lat);
                        flight.point.lng=mapController.changeLngToDMS(lnglat[0]);
                        flight.point.lat=mapController.changeLatToDMS(lnglat[1]);
                        data.push(flight.point);
                    });
                    return data
                },
                reLoad:function () {
                    if(this.dataTable&&$('#tip').is(":visible")){
                        this.dataTable.clear();
                        this.dataTable.rows.add(this.getData()).draw();
                    }

                },
                view_plane:function (did) {
                    map.setCenter(pl.flights[did].marker.getPosition());
                    map.setZoom(10);
                    pl.flights[did].marker.setIcon(pl.flights[did].selIcon,[32,32]);
                }
            };

            //右侧工具
            $('.right-float-menu').on('click','div[data-event]',function () {
                $(this).toggleClass("selected");
                 ruler.turnOff();
                //$(this).parent().siblings().find('div').removeClass("selected");
            }).on('click','div[data-event="isShowLine"]',function () {//开关航线。
                mapTools.isShowLine(pl)
            }).on('click','div[data-event="isFlightElements"]',function () {//开关飞行要素。
                $('#tip').hide();
                $('div[data-event="isPlantTable"]').removeClass('selected');
                 $('#elementspanel').toggle();
             }).on('click','div[data-event="isPlantLabel"]',function () {//开关飞行标签。
                        var isclick=$(this).is('.selected');
                        $.each(pl.flights,function (k,flight) {
                            if(isclick){
                                flight.marker.setIcon(flight.selIcon,[32,32]);
                                flight.marker.showInfoWindow();
                                flight.isCheck=true;
                            }else{
                                flight.marker.setIcon(flight.norIcon,[32,32]);
                                flight.marker.hideInfoWindow();
                                flight.isCheck=false;
                            }
                        })
             }).on('click','div[data-event="isPlantTable"]',function () {//开关列表。
                 $('#tip').toggle();
                $('div[data-event="isFlightElements"]').removeClass('selected');
                $('#elementspanel').hide();
                if($('#tip').is(":visible")){
                    aircraft_list.init();
                }

             });

            //开关空域要素
            $('#elementspanel').on('click','input',function (e) {
                var mapStyle=[];
                $('input[name="mapStyle"]:checked').each(function (e) {
                    mapStyle.push($(this).val());
                });
                c.setValues("mapStyle",mapStyle);
                if($(this).prop("checked")){
                    spaceLine.show($(this).val());
                }else{
                    spaceLine.hide($(this).val());
                }

            });

            //右键菜单
            var mapMenu=map.createContextMenu();
            var infoWindow= map.createInfoWindow();
            var ruler = map.createRangingTool();
            var rulerText='开始测距';
            var txtMenuItem = [
                {
                    text:'天气预报',
                    callback:function(e){
                        ruler.turnOff();
                         e= e||map.rightLngLat;
                        map.getWeather(e,function (json) {
                            /*var infoWindow = new BMap.InfoWindow("地址：北京市东城区王府井大街88号乐天银泰百货八层",null);
                             map.map.openInfoWindow(infoWindow,e);*/
                            var str = [];
                            str.push('<div style="color: #3366FF;">实时天气' + '</div>');
                            str.push('<div>省份/直辖市：' + json.province + '</div>');
                            str.push('<div>城市/区：' + json.city + '</div>');
                            str.push('<div>天气：' + json.weather + '</div>');
                            str.push('<div>温度：' + json.temperature + '℃</div>');
                            str.push('<div>风向：' + json.windDirection + '</div>');
                            str.push('<div>风力：' + json.windPower + ' 级</div>');
                            str.push('<div>空气湿度：' + json.humidity + '</div>');
                            str.push('<div>发布时间：' + json.reportTime + '</div>');
                            infoWindow.setContent(str.join("<br/>"));
                            infoWindow.open(map, e);
                        })}
                },
                {
                    text:'海拔高度',
                    callback:function(e){
                        ruler.turnOff();
                         e= e||map.rightLngLat;
                        mapController.getElevationForLocations(e,function (h) {
                            infoWindow.setContent(h+"米");
                            infoWindow.open(map, e);
                        });

                    }
                },
                {
                    text:"开始测距",
                    callback:function(e){
                        ruler.turnOn();
                        rulerText="关闭测距"
                    }
                },{
                    text:"关闭测距",
                    callback:function(e){
                        ruler.turnOff();
                    }
                }
            ];
            mapMenu.addItems(txtMenuItem);
            map.addContextMenu(mapMenu);
        }

    }

});


